<?php

namespace app\miniprograms\controller;

use controller\BasicAdmin;
use service\DataService;
use service\NodeService;
use service\ToolsService;
use think\App;;
use think\Db;
use think\Exception;
use app\common\model\Enum;

/**
 * Class Area
 * @package app\admin\controller
 * @author liuda <1576283429@qq.com>

 * @date
 */
class User extends BasicAdmin
{
    public $table = 'User';

    public function index(){
        $this->title = '用户列表';
        $where = '1=1';
        
        $card_no = $this->request->get('card_no');
        $code = $this->request->get('code');
        $excel = $this->request->get('excel');

        if(!empty($card_no)){
           $where .= " AND A.cards like '%$card_no%' ";
        }

        if(!empty($code)){
            $where .= " AND A.code = '$code' ";
        }

        $list =  Db::table('user')->alias('A')->field('A.id,A.cards, A.code,A.amount, A.user_name,A.disable ,A.create_at')->where($where)->order('A.id desc');

        if($excel=="1"){
            exit();
        }else{
            return parent::_list($list);
        }
    }

    public function daybook(){
        $this->title = '流水账列表';
        $where = '1=1';
        
        $card_no = $this->request->get('card_no');
        $code = $this->request->get('code');
        $excel = $this->request->get('excel');

        if(!empty($card_no)){
           $where .= " AND U.cards like '%$card_no%' ";
        }

        if(!empty($code)){
            $where .= " AND U.code = '$code' ";
        }

        $this->assign('btype', Enum::b_type_array);

        $list =  Db::table('daybook')->alias('A')->join('user U','A.user_id = U.id','LEFT')->field('A.old_amount,A.var_amount,A.amount,A.b_type,A.create_at,A.b_type,U.cards, U.code,A.amount, U.user_name')->where($where)->order('A.id desc');

        if($excel=="1"){
            exit();
        }else{
            return parent::_list($list);
        }
    }
    




    /**
     * 表单数据默认处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _form_filter(&$data)
    {
        if ($this->request->isPost()) {    //添加处理
            $amount = $this->request->post('amount');
            if(!is_numeric($amount)){
                $this->error("充值金额必须为数字");
                return false;
            }
        }
    }

    /*
     * 编辑价格
     */
    public function edit()
    {
        return $this->_form($this->table, 'form');
    }


    //充值列表
    public function setdisable(){
        $id =  $this->request->get('id');
        $val =  $this->request->get('val');
        try{
            Db::table('user')->where(['id'=>$id])->update(['disable'=>$val]);
            $this->success('修改成功!', '');
        }catch (Exception $e){
            $this->error('修改失败，请稍后再试！'.$e);
        }
    }

    //充值
    public function chongzhi(){
        return $this->_form_half($this->table, 'form');
    }

    public function _form_result_half($data)
    {
        $amount = (float)$data['amount'];
        $rg_remark=$data['rg_remark'];
        $rg_user_id = session('user.id');
        $amount=$amount*100;

        $user = Db::table('user')->where("id",$data['id'])->find();
        if(!$user){
            $this->error('user is empty!');
            return false;
        }
       
        $no = Enum::orderNo(Enum::order_type_rgcz);
        $time =date('Y-m-d H:i:s',time());

        $data=[
            'user_id' => $user['id'],
            'open_id' => $user['open_id'],
            'union_id' => $user['union_id'],
            'type' => Enum::b_type_rgcz,
            'trade_no' => "",
            'card_no' => "",
            'order_no' => $no,
            'apsid' => "",
            'pay_status' => Enum::PAY_SUCESS,
            'create_at' => $time,
            'update_at' => $time,
            'czamount' => $amount,
            'amount' => $amount,
            'gift' => 0,
            'rg_user_id'=>$rg_user_id,
            'rg_remark'=>$rg_remark
        ];

        //插入数据
        $n_amount = $user['amount'] + $amount;

        $book=[
            'user_id' => $user['id'],
            'b_type' => Enum::b_type_rgcz,
            'b_id' => 0,
            'b_no' => $no,
            'create_at' => $time,
            'old_amount' =>$user['amount'],
            'var_amount' =>$amount ,
            'amount' => $n_amount
        ];

        Db::startTrans();
        try {
            $id=Db::table('charge')->insertGetId($data);
            $book['b_id'] =$id;
            //用户的钱变化
            $c = Db::table('user')->where('id',$user['id'])->setInc('amount',$amount);
            Db::table('daybook')->strict(false)->insert($book);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('数据更新异常! - '.$e);
            return false;
        }

        $this->success('保存成功!', '');
    }


    public function test()
    {
        $old_apsid="99f66fe77d1ff57b97e6908b63e77d76"; //$post["oldapsid"];
        //获取原用户信息
        $map=[
            ['apsid', '=', $old_apsid]
        ];
        $data_old = Db::connect('db_old')->table('user')->where($map)->find();
        if(empty($data_old)){
            return $this->renderError("未找到历史用户信息,请联系管理员");
        }

        if($data_old["blance"]==1){
            return $this->renderSuccess(99);//已转移过了.不需要继续
        }

        //找到对应的数据
        $map=[
            ['apsid', '=', $old_apsid]
        ];
        $user = Db::table('user')->where($map)->find();
        if(empty($user)){
            return $this->renderError("新系统用户信息无法匹配,请联系管理员");
        }

        //1 转移数据  2转移且金额同步了
        if($user["is_transfer"]==2){
            return $this->renderSuccess(99);//已转移过了.不需要继续
        }
        $amount =  $data_old["amount"];

        //同步用户现在的金额

        $no = Enum::orderNo(Enum::order_type_cscz);
        $time =date('Y-m-d H:i:s',time());

        $data=[
            'user_id' => $user['id'],
            'open_id' => $user['open_id'],
            'union_id' => $user['union_id'],
            'type' => Enum::b_type_cscz,
            'trade_no' => "",
            'card_no' => "",
            'order_no' => $no,
            'apsid' => "",
            'pay_status' => Enum::PAY_SUCESS,
            'create_at' => $time,
            'update_at' => $time,
            'czamount' => $amount,
            'amount' => $amount,
            'gift' => 0
        ];

        //插入数据
        $n_amount = $user['amount'] + $amount;

        $book=[
            'user_id' => $user['id'],
            'b_type' => Enum::b_type_cscz,
            'b_id' => 0,
            'b_no' => $no,
            'create_at' => $time,
            'old_amount' =>$user['amount'],
            'var_amount' =>$amount ,
            'amount' => $n_amount
        ];

        Db::startTrans();
        try {
            $id=Db::table('charge')->insertGetId($data);
            $book['b_id'] =$id;
            //用户的钱变化
            $c = Db::table('user')->where('id',$user['id'])->setInc('amount',$amount);
            Db::table('daybook')->strict(false)->insert($book);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('数据更新异常! - '.$e);
            return false;
        }

        //用户的绑定卡信息已经同步过去了.把用户的余额全部转过去,做一次性充值.这样就断掉那边的金额了.
        return $this->renderSuccess(1); 
    }
    

}